package ro.ubbcluj.cs.bs.backend.model;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import java.io.Serializable;
import java.util.UUID;

@MappedSuperclass
public abstract class AbstractModel implements Serializable {
    private static final long serialVersionUID = 1L;

    private String uuid;

    protected AbstractModel() {
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (getUuid() == null ? 0 : getUuid().hashCode());

        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }

        final AbstractModel other = (AbstractModel) obj;
        if (getUuid() == null) {
            if (other.getUuid() != null) {
                return false;
            }
        } else if (!getUuid().equals(other.getUuid())) {
            return false;
        }

        return true;
    }

    @Column(name = "uuid", nullable = false, length = 36, unique = true)
    public String getUuid() {
        ensureUuid();
        return uuid;
    }

    private void setUuid(String uuid) {
        this.uuid = uuid;
    }

    @PrePersist
    public void onPrePersist() {
        ensureUuid();
    }

    private void ensureUuid() {
        if (uuid == null) {
            setUuid(UUID.randomUUID().toString());
        }
    }
}
